const util = require("util");
const axios = require("axios");

const { User } = require("../models/user");
const { generateToken } = require("../../core/util");
const { Ip } = require("@services/ip");
const { redis } = require("@core/redis");

class WXManager {
  static async codeToToken(code, ctx) {
    // code
    // code 小程序生成 微信
    // openid 唯一标识

    // 显示注册
    // 唯一标识·
    // code
    // appid
    // appsecret
    // url
    const url = util.format(
      global.config.wx.loginUrl,
      global.config.wx.appId,
      global.config.wx.appSecret,
      code
    );

    const result = await axios.get(url);

    if (result.status !== 200) {
      throw new global.errs.AuthFailed("openid获取失败");
    }

    const errCode = result.data.errcode;
    const errMsg = result.data.errmsg;
    if (errCode) {
      throw new global.errs.AuthFailed("openid获取失败: " + errMsg);
    }

    // opedId
    // 建立档案 user uid
    // openId
    let token = await redis.get(`token:${result.data.openid}`);
    if (!token) {
      // 判断数据库是否存在微信用户 opendid
      let user = await User.getUserByOpenid(result.data.openid);

      // 如果不存在，就创建一个微信小程序用户
      if (!user) {
        user = await User.createUserByOpenid(result.data.openid);
      }
      token = generateToken(user.uid, user.power);
      // 更新用户地区
      const res = await Ip.get(ctx);

      let { nation, province, city, district } = res.data.result.ad_info;

      user.update({ area: `${nation}${province}${city}${district}` });
      // 保存token
      redis.set(`token:${result.data.openid}`, token, "EX", 60 * 60 * 2);
      return token;
    } else {
      return token;
    }
  }
}

module.exports = {
  WXManager,
};
